// ✅ 正确：使用标准的vue模块路径
import { ref, onMounted, onBeforeUnmount } from "vue";

// 鼠标移动Hook
const useMouseTranslate = (el) => {
  const isMouseDown = ref(false);
  const isMoving = ref(false);
  const x = ref(0); // 鼠标x坐标

  const moveHandle = (e) => {
    e.preventDefault();
    if (!isMouseDown.value) return;
    x.value = e.clientX;
    isMoving.value = true;
  };

  const downHandle = (e) => {
    e.preventDefault();
    isMoving.value = false;
    isMouseDown.value = true;
    x.value = e.clientX;

    bindMoveEvents();
  };

  const upHandle = (e) => {
    e.preventDefault();
    isMouseDown.value = false;
    isMoving.value = false;

    unbindMoveEvents();
  };

  const bindMoveEvents = () => {
    document.addEventListener("mouseup", upHandle);
    document.addEventListener("mousemove", moveHandle);
  };

  const unbindMoveEvents = () => {
    document.removeEventListener("mousemove", moveHandle);
    document.removeEventListener("mouseup", upHandle);
  };

  onMounted(() => {
    if (el.value) {
      el.value.addEventListener("mousedown", downHandle);
    } else {
      console.error("❌ el.value 为空，无法绑定事件！");
    }
  });

  const off = () => {
    el.value?.removeEventListener("mousedown", downHandle);
    unbindMoveEvents();
  };

  onBeforeUnmount(() => {
    off();
  });

  return {
    isMouseDown,
    isMoving,
    x,
  };
};

export { useMouseTranslate };
